<template>
  <el-container class="body-container">
    <div class="sidebar">
      <div class="header">
        <span id="status-dropdown">
          <div class="avatar status-selector">
            <img v-if="realAvatarUrl" :src="realAvatarUrl">
            <span v-else>{{ userInfo.username }}</span>
            <span class="status">
              <div class="icon-container">
                <status-online-avatar v-if="onlineStatus === 'online'"></status-online-avatar>
                <status-away-avatar v-else-if="onlineStatus === 'away'"></status-away-avatar>
                <status-offline-avatar v-else-if="onlineStatus === 'offline'"></status-offline-avatar>
                <status-dnd-avatar v-else-if="onlineStatus === 'dnd'"></status-dnd-avatar>
              </div>
            </span>
            <div class="status-edit">
              <el-dropdown trigger="click" @command="handleOnlineStatus">
                <span>
                  <svg t="1525682970585" viewBox="0 0 1024 1024" version="1.1" p-id="1166" width="13" height="13"><path d="M180.177 258.603c-32.209 0-49.892 39.532-29.407 65.799l316.399 405.35c23.526 30.156 67.296 30.156 90.824 0l316.079-405.394c20.485-26.227 2.8-65.757-29.408-65.757l-664.487 0z" p-id="1167" fill="#111111"></path></svg>
                </span>
                <el-dropdown-menu slot="dropdown" style="margin-top: -15px;">
                  <el-dropdown-item command="online">在线</el-dropdown-item>
                  <el-dropdown-item command="away">离开</el-dropdown-item>
                  <el-dropdown-item command="dnd">
                    <div>请勿打扰</div>
                    <div class="status-tooltip">停用推送通知</div>
                  </el-dropdown-item>
                  <el-dropdown-item command="offline">离线</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </span>
        <h4 class="nickname">{{ userInfo.nickname }}</h4>
        <a class="dropdown-icon" title="主菜单">
          <el-dropdown trigger="click" @command="handleCommand">
            <span>
              <svg width="16px" height="10px" viewBox="0 0 16 10" version="1.1"><g stroke="none" stroke-width="1" fill="inherit" fill-rule="evenodd"><g transform="translate(-188.000000, -38.000000)" fill-rule="nonzero" fill="inherit"><g><g><g transform="translate(188.000000, 38.000000)"><path d="M15.5,0 C15.776,0 16,0.224 16,0.5 L16,1.5 C16,1.776 15.776,2 15.5,2 L0.5,2 C0.224,2 0,1.776 0,1.5 L0,0.5 C0,0.224 0.224,0 0.5,0 L15.5,0 Z M15.5,4 C15.776,4 16,4.224 16,4.5 L16,5.5 C16,5.776 15.776,6 15.5,6 L0.5,6 C0.224,6 0,5.776 0,5.5 L0,4.5 C0,4.224 0.224,4 0.5,4 L15.5,4 Z M15.5,8 C15.776,8 16,8.224 16,8.5 L16,9.5 C16,9.776 15.776,10 15.5,10 L0.5,10 C0.224,10 0,9.776 0,9.5 L0,8.5 C0,8.224 0.224,8 0.5,8 L15.5,8 Z"></path></g></g></g></g></g></svg>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="editPersonalInfo">账号设置</el-dropdown-item>
              <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
              <el-dropdown-item command="logout" divided>注销登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </a>
        <edit-personal-info ref="editPersonalInfoDlg"></edit-personal-info>
        <change-password ref="changePasswordDlg"></change-password>
      </div>
      <div class="channel-search-container">
           <el-select v-model="selectedChannelGroup" clearable value-key="groupId"  filterable placeholder="请选择">
            <el-option
              v-for="item in allGroups" 
              :key="item.groupId"
              :label="item.groupName"
              :value="item">
            </el-option>
          </el-select>
      </div>
      <div class="channel-container" v-bind:style="{height: channelListHeight}">
        <ul class="nav-channel first-nav-channel">
          <li class="channel-header">
            <span>群聊</span>
            <button class="add-channel-btn" title="创建群聊" @click="openCreateCommonChannelGroupDlg">+</button>
            <create-channel-group ref="createCommonChannelGroupDlg" :categoryId="'common'" :channel-group="selectedChannelGroup" @onChannelGroupCreate="onChannelGroupCreate"></create-channel-group>
          </li>
          <li class="channel-item" v-for="(item, index) in commonChannelGroups"  :key="item.groupId" :class="{'channel-item channel-item-active' : selectedChannelGroup.groupId === item.groupId}" @click="selectChannelGroup(item, index)">
            <div> 
              <div class="has-close"> 
                <div class="status">
                  <group-icon :selected="selectedChannelGroup.groupId === item.groupId"></group-icon>
                </div>
                <a :class="{'channel-item-name channel-item-name-selected' : selectedChannelGroup.groupId === item.groupId, 'channel-item-name': selectedChannelGroup.groupId !== item.groupId}">{{ item.groupName==null?item.cusername+'创建的群聊':item.groupName }}</a>
                <div :class="{'unread-message-count':  item.unreadMessagesCount&&item.unreadMessagesCount > 0, 'unread-message-count-hide': item.unreadMessagesCount==null||item.unreadMessagesCount==0}">{{ item.unreadMessagesCount>0?item.unreadMessagesCount : "" }}</div>
                <span class="btn-close" @click="doHideChannel(item.groupId)">×</span>
            </div>
          </div>
          </li>
        </ul>
        <ul class="nav-channel">
          <li class="channel-header">
            <span>私聊</span>
            <button class="add-channel-btn" title="创建私聊" @click="openCreatePrichatChannelDlg">+</button>
            <create-prichat-channel-group ref="createPrivateChanneDlg" @onChannelCreated="onPrichatChannelCreated"></create-prichat-channel-group>
          </li>
          <li class="channel-item" v-for="(item, index) in this.myPrichatChannelGroups"  :key="item.groupId" :class="{'channel-item channel-item-active' : selectedChannelGroup.groupId === item.groupId}" @click="selectChannelGroup(item, index)">
            <div>
              <div class="has-close"> 
                <div class="status">
                  <group-icon :selected="selectedChannelGroup.groupId === item.groupId"></group-icon>
                </div> 
                <a :class="{'channel-item-name channel-item-name-selected' : selectedChannelGroup.groupId === item.groupId, 'channel-item-name': selectedChannelGroup.groupId !== item.groupId}"> {{ formatGroupName(item) }}</a>
                <div :class="{'unread-message-count':  item.unreadMessagesCount&&item.unreadMessagesCount > 0, 'unread-message-count-hide': item.unreadMessagesCount==null||item.unreadMessagesCount==0}">{{ item.unreadMessagesCount>0?item.unreadMessagesCount : "" }}</div>
                <span class="btn-close" @click="doHideChannel(item.groupId)">×</span>
              </div>
            </div>
          </li>
        </ul>
        <ul class="nav-channel first-nav-channel">
          <li class="channel-header">
            <span>客服工作人员群组</span>
            <button class="add-channel-btn" title="创建群聊" @click="openCreateCswChannelGroupDlg">+</button>
            <create-channel-group ref="createCswChannelGroupDlg" :categoryId="'csw'"  @onChannelGroupCreate="onChannelGroupCreate"></create-channel-group>
          </li>
          <li class="channel-item" v-for="(item, index) in cswChannelGroups"  :key="item.groupId" :class="{'channel-item channel-item-active' : selectedChannelGroup.groupId === item.groupId}" @click="selectChannelGroup(item, index)">
            <div> 
                <div class="status">
                  <group-icon :selected="selectedChannelGroup.groupId === item.groupId"></group-icon>
                </div>
                <a :class="{'channel-item-name channel-item-name-selected' : selectedChannelGroup.groupId === item.groupId, 'channel-item-name': selectedChannelGroup.groupId !== item.groupId}">{{ item.groupName==null?'客人'+item.cusername+item.cuserid:item.groupName }}</a>
                <div :class="{'unread-message-count':  item.unreadMessagesCount&&item.unreadMessagesCount > 0, 'unread-message-count-hide': item.unreadMessagesCount==null||item.unreadMessagesCount==0}">{{ item.unreadMessagesCount>0?item.unreadMessagesCount : "" }}</div>
            </div>
          </li>
        </ul>
        <ul class="nav-channel first-nav-channel">
          <li class="channel-header">
            <span>我的客户</span>
            <button class="add-channel-btn" title="创建群聊" @click="openCreateCssChannelGroupDlg">+</button>
            <create-channel-group ref="createCssChannelGroupDlg" :categoryId="'css'"  @onChannelGroupCreate="onChannelGroupCreate"></create-channel-group>
          </li>
          <li class="channel-item" v-for="(item, index) in cssChannelGroups"  :key="item.groupId" :class="{'channel-item channel-item-active' : selectedChannelGroup.groupId === item.groupId}" @click="selectChannelGroup(item, index)">
            <div> 
                <div class="status">
                  <group-icon :selected="selectedChannelGroup.groupId === item.groupId"></group-icon>
                </div>
                <a :class="{'channel-item-name channel-item-name-selected' : selectedChannelGroup.groupId === item.groupId, 'channel-item-name': selectedChannelGroup.groupId !== item.groupId}">{{ item.groupName==null?'客人'+item.cusername+item.cuserid:item.groupName }}</a>
                <div :class="{'unread-message-count':  item.unreadMessagesCount&&item.unreadMessagesCount > 0, 'unread-message-count-hide': item.unreadMessagesCount==null||item.unreadMessagesCount==0}">{{ item.unreadMessagesCount>0?item.unreadMessagesCount : ''}}</div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="content">
       <message-dialog :selected-channel-group="selectedChannelGroup" @clearChannelGroupUnreadMessages="clearChannelGroupUnreadMessages" ref="messageDialog"></message-dialog>
    </div>
  </el-container>
</template>

<script>
import { ImClient } from '@/client/ImClient'
import { listMyChannelGroups } from '@/api/mdp/im/group/imGroup'
import { listImGroupMessage } from '@/api/mdp/im/group/imGroupMessage' 
import { listMyPrichatChannelGroups,listImPrichatMessage } from '@/api/mdp/im/prichat/imPrichatMessage'
import { updateOnlineStatus } from '@/api/user'
import GroupIcon from '@/views/mdp/im/svg/groupIcon'
import StatusOnlineIcon from '@/views/mdp/im/svg/statusOnlineIcon'
import StatusOfflineIcon from '@/views/mdp/im/svg/statusOfflineIcon'
import StatusAwayIcon from '@/views/mdp/im/svg/statusAwayIcon'
import StatusDndIcon from '@/views/mdp/im/svg/statusDndIcon'
import StatusOnlineAvatar from '@/views/mdp/im/svg/statusOnlineAvatar'
import StatusOfflineAvatar from '@/views/mdp/im/svg/statusOfflineAvatar'
import StatusDndAvatar from '@/views/mdp/im/svg/statusDndAvatar'
import StatusAwayAvatar from '@/views/mdp/im/svg/statusAwayAvatar'


import EditPersonalInfo from '@/views/mdp/im/user/editPersonalInfo' 
import CreatePrichatChannelGroup from'@/views/mdp/im/channel/createPrichatChannelGroup' 
import CreateChannelGroup from '@/views/mdp/im/channel/createChannelGroup' 
import ChangePassword from '@/views/mdp/im/user/changePassword'
import MessageDialog from '@/views/mdp/im/dialog/messageDialog' 
import seq from '@/common/js/sequence';//全局公共库


import { mapGetters } from 'vuex'
const USER_CHANNEL_LIST_SIZE = 16

export default { 

  data() { 
    return { 
      onlineStatus: 'online',
      myChannelGroups: [],//{sendUserid:'',sendUsername:'',toUserid:'',groupId:'',unreadMessages:[],unreadMessagesCount:0}
      myPrichatChannelGroups:[], //{sendUserid:'',sendUsername:'',toUserid:'',groupId:'',unreadMessages:[],unreadMessagesCount:0}
      selectedChannelGroup:{},//{sendUserid:'',sendUsername:'',toUserid:'',groupId:'',unreadMessages:[],unreadMessagesCount:0},
      searchKey: '', 
      channelListHeight: ''
    }
  },
  watch:{
    $route(route){
      this.initGroupByRouteQuery();
      this.initPrichatByRouteQuery();
      
    }
  },
  methods: {
    handleCommand(command) {
      switch(command) {
        case 'logout':
          this.logout()
          break
        case 'editPersonalInfo':
          this.$refs.editPersonalInfoDlg.$emit('openDialog')
          break
        case 'changePassword':
          this.$refs.changePasswordDlg.$emit('openDialog')
          break
      }
    },
    handleOnlineStatus(command) {
      if(this.onlineStatus !== command) {
        this.onlineStatus = command
       /**  updateOnlineStatus(this.userInfo.userid, this.onlineStatus)
        .catch(error => {
          ////outputError(this, error)
        })
        **/
      }
    },
    initGroupByRouteQuery(){
      if(this.$route.query.categoryId=='css'){//客户咨询的话 
        var sendContent=this.$route.query.sendContent;
        var sendObject=this.$route.query.sendObject;

        let currentUser = this.userInfo; 
        let channel = {
          msgId:seq.sn(),
          msgType: 'group',
          groupId:'css_'+currentUser.userid, 
          categoryId:'css',
          sendUserid: currentUser.userid,
          sendUsername: currentUser.username,  
          sendContent:sendContent, 
          sendObject:sendObject,
          sendTime:new Date().getTime()
        } 
        var index=this.myChannelGroups.findIndex(i=>i.groupId==channel.groupId)
        if(index>=0){ 
          channel.action="newMessage"

          this.selectChannelGroup(this.myChannelGroups[index],index)
          this.$refs.messageDialog.onSentMessage(channel);
          //直接发送消息
        }else{ 
          channel.action="channelGroupCreate",
          channel.groupName=sendContent
          channel.cuserid=currentUser.userid
          channel.cusername=currentUser.username
          channel.categoryId='css'
          channel.users=[{userid:currentUser.userid,username:currentUser.username}]
          this.onChannelGroupCreate(channel)
        }
      } 
    },
    initPrichatByRouteQuery(){
      if(this.$route.query.toUserid){
        var toUserid=this.$route.query.toUserid;
        
        var toUsername=this.$route.query.toUsername;
        if(!toUsername){
          toUsername=toUserid;
        }
        var sendContent=this.$route.query.sendContent;
        var sendObject=this.$route.query.sendObject;
        let currentUser = this.userInfo;
        var groupUserids=[currentUser.userid,toUserid];
        groupUserids=groupUserids.sort();
        let channel = {
          msgId:seq.sn(),
          msgType: 'prichat',
          groupId:groupUserids.join("_"),
          groupName:"与"+toUsername+"的聊天",
          isPrichat:'1',
          sendUserid: currentUser.userid,
          sendUsername: currentUser.username, 
          toUserid:toUserid,
          toUsername: toUsername, 
          sendContent:sendContent,
          sendObject:sendObject
        } 
        this.onPrichatChannelCreated(channel);
      }
    },
    logout() { 
      this.$store.dispatch('LogOut').then(() => {
       this.$router.push("/login");
      }) 
    },
    openCreatePrichatChannelDlg() {
      this.$refs.createPrivateChanneDlg.$emit('openDialog', 'add')
    },
    openCreateCommonChannelGroupDlg() {
      this.$refs.createCommonChannelGroupDlg.$emit('openDialog', 'add')
    },
    openCreateCssChannelGroupDlg() {
      this.$refs.createCssChannelGroupDlg.$emit('openDialog', 'add')
    },
    openCreateCswChannelGroupDlg() {
      this.$refs.createCswChannelGroupDlg.$emit('openDialog', 'add')
    },        
    selectChannelGroup(channelGroup, index) {  
      channelGroup.unreadMessagesCount=0;
      this.$store.getters.imClient.db().groupMessageState.where("groupId").equals(channelGroup.groupId).modify({unreadMessagesCount:0}) 
      this.selectedChannelGroup = Object.assign({},channelGroup)
    },
    onOnlineStatusChanged(message) {
      if(message.userid === this.userInfo.userid) {
        return
      }
      for(let userChannel of this.myChannelGroups) {
        if(userChannel.toUserId == null) {
          continue
        }
        if(userChannel.toUserId === message.userid) {
          userChannel.toUserOnlineStatus = message.onlineStatus
          break
        }
      }
    },
    formatGroupName:function(group){
      if(group.groupName){
        return group.groupName
      }
      if(this.userInfo.userid==group.sendUserid){
        if(group.toUsername){
          return group.toUsername
        }else{ 
          return group.toUserid
        }
      }else if(this.userInfo.userid==group.toUserid){
        if(group.sendUsername){
          return group.sendUsername;
        }else{
          return group.sendUserid
        }
        
      }
    },
    onNicknameChanged(message) {
       
      for(let myChannelGroup of this.myChannelGroups) {
        if(myChannelGroup.toUserId === message.userid) {
          if(myChannelGroup.channelDisplayName == null || myChannelGroup.channelDisplayName === '') {
            myChannelGroup.channelDisplayName = message.nickname
          }
          return
        }
      }   
    },
    onAvatarChanged(message) {
      if(message.userid === this.userInfo.userid) {
        let currentUser = this.userInfo
        currentUser.avatarUrl = this.userInfo.avatarUrl = ''
        currentUser.avatarUrl = this.userInfo.avatarUrl = message.avatar   
      }
    },
    onUnreadMessage(message) {  
      var that=this; 
      console.log("进来啦") 
        if(message.action==='messageStateReport'){
          return;
        }  
            console.log("cccccccccccccccccccccccccccccc----item");
           // console.log(item)
        if(message.msgType=='prichat'){//私聊消息送达我这里 
          //下面处理消息在客户端显示问题 
            //设置未读消息unreadMessages,如双方为首次聊天，将其加入聊天会话队列中
            if(!this.myPrichatChannelGroups.some(i=>i.groupId==message.groupId)){//如果不在私聊会话组中，则添加会话组，并添加未读消息 
              message.isPrichat='1'
              message.unreadMessagesCount=1
              that.$set(that.myPrichatChannelGroups,0,message)
             }else{//如果在私聊会话组中，则添加会话组未读消息
            var index=0;
              this.myPrichatChannelGroups.forEach(i=>{
                if(i.groupId==message.groupId){ 
                    if(!i.unreadMessagesCount){
                      i.unreadMessagesCount=0;
                    }
                    i.unreadMessagesCount=i.unreadMessagesCount+1;
                    that.$set(that.myPrichatChannelGroups,index,i)
                    console.log(that.myPrichatChannelGroups[index]);
                }
                index=index+1;
              })
            } 
            console.log(this.myPrichatChannelGroups)
        }else if(message.msgType=='group'){//如果是群聊消息到达我这里
            //设置未读消息unreadMessages,如双方为首次聊天，将其加入聊天会话队列中
            if(!this.myChannelGroups.some(i=>i.groupId==message.groupId)){//如果不在群聊会话组中，则添加会话组，并添加未读消息
              //查询后台获取会话组信息（暂时不处理）
              var group={
                groupId:message.groupId,
                groupName:message.sendUsername+'发起的群聊',
                isPrichat:'0', 
                unreadMessagesCount:1
                }  
              that.$set(that.$data.myChannelGroups,0,group); 

            }else{//如果在群聊会话组中，则添加会话组未读消息
              var index=0;
              for(var k=0;k<this.myChannelGroups.length;k++){
                var i=this.myChannelGroups[k];
                if(i.groupId==message.groupId){   
                  
                    if(!i.unreadMessagesCount){
                      i.unreadMessagesCount=0;
                    }
                    i.unreadMessagesCount=i.unreadMessagesCount+1;
                  that.$set(that.$data.myChannelGroups,index,i); 
                  break;
                }
                index=index+1;
              }  
            } 
        }   
    },
    onHisMessage(message) { 
    },
    onJoinChannelGroup(message) {
      var that=this;
      let index = this.myChannelGroups.findIndex(item => item.groupId === message.groupId)
      if(index > -1) {
        return
      }else{ 
        this.myChannelGroups.push(message); 
      }
    }, 
    onChannelGroupNameChanged(message) {
      var that=this;
      var i=0;
      for(let group of this.myChannelGroups) { 
        if(group.groupId === message.groupId) {
          group.groupName = message.groupName
           that.$set(that.$data.myChannelGroups,i,group);  
          return
        }
        i=i+1;
      }
    },
     
    onLeaveChannelGroup(message) {
 
      
    }, 
    onChannelGroupRemove(message) { 
    },
    onUserOnline() {
      this.onlineStatus = 'online' 
    },
    onUserOffline() {
      this.onlineStatus = 'offline'
       
    },    
    initImClient() {
    	var outUrl= process.env.WEBSOCKET_URL;
    	var wsProtocol="ws";
    	if(window.location.protocol.indexOf("https")>=0){
    		wsProtocol="wss";
    	}
    	if(outUrl.indexOf("${wsProtocol}")>=0){
    		outUrl=outUrl.replace("${wsProtocol}",wsProtocol);
    	}
      if(outUrl.indexOf("${curlHost}")>=0){
        var curlHost= window.location.host; //   返回 mp.csdn.net
        outUrl=outUrl.replace("${curlHost}",curlHost);
		  }

      let wsUrl = outUrl + '?accessToken=' + this.token
    		  console.log("初始化ImClient>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>..."+wsUrl)
      const imClient = new ImClient(wsUrl, 3 * 1000,this.userInfo.userid)
      console.log("ImClient创建成功，实例为 imClient")
      this.$store.dispatch('setImClient', imClient)
      imClient.bindOnlineStatusChanged(this.onOnlineStatusChanged)
      imClient.bindNicknameChanged(this.onNicknameChanged)
      imClient.bindAvatarChanged(this.onAvatarChanged)
      imClient.bindUnreadMessage(this.onUnreadMessage)
      imClient.bindHisMessage(this.onHisMessage)
      imClient.bindChannelGroupCreate(this.bindChannelGroupCreate)
      imClient.bindJoinChannelGroup(this.onJoinChannelGroup)
      imClient.bindChannelGroupNameChanged(this.onChannelGroupNameChanged)
      imClient.bindLeaveChannelGroup(this.onLeaveChannelGroup)
      imClient.bindChannelGroupRemove(this.onChannelGroupRemove)
      imClient.bindUserOnline(this.onUserOnline)
      imClient.bindUserOffline(this.onUserOffline)
      imClient.bindOnloadDataFromServer(this.onLoadDataFromServer) 
      imClient.connect(this.bindToChannelGroups)
    },
    bindToChannelGroups(imClient) {
        
    },
    onPrichatChannelCreated(channel) {
      this.selectedChannelGroup = channel
      channel.groupName=channel.toUsername;
      //this.$router.push({ name: 'messageDialog', params: { groupId: channel.groupId, isPrichat:'1' }})
      for(let userChannel of this.myPrichatChannelGroups) {
        if(userChannel.groupId === channel.groupId) {
          return
        }
      }
      this.myPrichatChannelGroups.unshift(channel);
      //this.myChannelGroups.unshift(channel)
      if(this.myPrichatChannelGroups.length > USER_CHANNEL_LIST_SIZE) {
        this.myPrichatChannelGroups.pop()
      }
    },
    onChannelGroupCreate(group) {
      console.log(group);
      this.selectedChannelGroup = Object.assign({},group);
      //
      if(!this.myChannelGroups.some(i=>i.groupId==group.groupId)){
        console.log("xxxxxxxxxxxxxffffffffffffffffffffffffffffff");
    	  this.myChannelGroups.push(group)
      }else{
        return;
      }
      let imClient = this.$store.getters.imClient
      console.log("store拿到的imClient")
      console.log(imClient)
      group.action='channelGroupCreate'
      group.msgType='group'
      if(group.branchId==null||group.branchId==''||group.branchId==undefined){
        group.branchId=this.userInfo.branchId
      }
      if(group.shopId==null||group.shopId==''||group.shopId==undefined){
        if(this.userInfo.shopId==null||this.userInfo.shopId==''||this.userInfo.shopId==undefined){
          group.shopId=group.branchId
        }else{
          group.shopId=this.userInfo.shopId
        } 
      }
      imClient.send(group); 
    },
    bindChannelGroupCreate(group) {
      console.log("进来bindChannelGroupCreate");
      console.log(group); 
      //this.selectedChannelGroup = Object.assign({},group);
      //
       console.log(this.myChannelGroups); 
      if(!this.myChannelGroups.some(i=>i.groupId==group.groupId)){
        console.log("xxxxxxxxxxxxxffffffffffffffffffffffffffffff");
    	  this.myChannelGroups.push(group)
      } else{ 
        var oldGroupIndex=this.myChannelGroups.findIndex(item => item.groupId == group.groupId)
         console.log("xxxxxxxxxxxx");
        console.log(oldGroupIndex);
        var oldGroup=this.myChannelGroups[oldGroupIndex]
        this.myChannelGroups.splice(oldGroupIndex,1);
         console.log(this.myChannelGroups); 
        this.myChannelGroups.push(group);
        console.log(this.myChannelGroups);
      } 
    },
    doHideChannel(groupId) {
      hideChannel(this.userInfo.userid, groupId)
      .then(response => {
        if(response.data > 0) {
          let index = this.myChannelGroups.findIndex(item => item.groupId === groupId)
          if(index === -1) {
            return
          }
          this.myChannelGroups.splice(index, 1)
          if(this.selectedChannelGroup.groupId === groupId) {
            this.selectedChannelGroup.groupId = ''
            this.$router.push({ name: 'welcome' })
          }          
        }
      })
      .catch(error => {
        ////outputError(this, error)
      })      
    },
    doSearchChannel() {
      if(!this.searchKey.trim()) {
        return
      }
      this.myChannelGroups = []
      searchUserChannel(this.userInfo.userid, this.searchKey)
      .then(response => {
        this.myChannelGroups = response.data
      })
      .catch(error => {
        ////outputError(this, error)
      })        
    },
    onSearchInputKeyUp(event) {
      if(!this.searchKey.trim()) {
        listUserChannels(this.userInfo.userid, USER_CHANNEL_LIST_SIZE)
        .then(response => {
          this.myChannelGroups = response.data
        })
        .catch(error => {
          ////outputError(this, error)
        })
        return
      }
      if(event.keyCode === 13) {
        this.doSearchChannel()
      }
    },
    clearChannelGroupUnreadMessages: function(channelGroup){
         
    },
    showCssGroupBizStatusDesc: function(group){
      if(group.bizStatus=='0'){
        return '待分配客服'
      }else if(group.bizStatus=='1'){
        return '客服接待中'
      }else if(group.bizStatus=='2'){
        return '已结束'
      }
    },
    showCssGroupLastUnreadMessage: function(group){ 
      if(group.unreadMessages){
        var length=group.unreadMessages.length;
        if(length>0){ 
          return group.unreadMessages.pop();
        }
      }
    },
    onLoadDataFromServer(event,data){
       if( data && data.length<=0){
        return;
      }
      this.loadImDataFromLocal(event);
      // listMyChannelGroups / listImGroupMessage / listImPrichatMessage/ listMyPrichatChannelGroups
 
    },
    loadImDataFromLocal(event){ 
      var that = this;
      if(event=='listMyChannelGroups'){
        this.$store.getters.imClient.db().groupMessageState.where({isPrichat:'0',guStatus:'1',gstatus:'1'}).sortBy('sendTime',items=>{
          that.myChannelGroups=items;  
          if(that.selectedChannelGroup==null && items.length>0){
            that.selectedChannelGroup=items[0]
          }
          that.initGroupByRouteQuery();

        }).catch(e=>{
          console.log(e);
        });
      }else if(event=='listMyPrichatChannelGroups'){
        this.$store.getters.imClient.db().groupMessageState.where({isPrichat:'1'}).sortBy('sendTime',items=>{
          
          items.forEach(i=>i.groupName=that.formatGroupName(i))
          that.myPrichatChannelGroups=items; 
          if(that.selectedChannelGroup==null && items.length>0){
            that.selectedChannelGroup=items[0]
           }
           that.initPrichatByRouteQuery();
        }).catch(e=>{
          console.log(e);
        });
      }
    }, 
  },
  computed: { 
    ...mapGetters([
      'userInfo','token'
    ]),
    realAvatarUrl() {
      if(this.userInfo.avatarUrl == null || this.userInfo.avatarUrl.trim() === '') {
        return null
      }
      if(!this.userInfo.avatarUrl.startsWith('http:') && !this.userInfo.avatarUrl.startsWith('https:')) {
        return process.env.BASE_API + '/users/' + this.userInfo.userid + '/avatar?width=36&height=36&rdm=' + Math.random()
      }
      return this.userInfo.avatarUrl + (this.userInfo.avatarUrl.indexOf('?') > -1 ? '&' : '?') + 'rdm=' + Math.random()
    }, 
    cssChannelGroups(){
      return this.myChannelGroups.filter(i=>i.categoryId=='css');
    },
    cswChannelGroups(){
      return this.myChannelGroups.filter(i=>i.categoryId=='csw');
    },
    commonChannelGroups(){
      return this.myChannelGroups.filter(i=>i.categoryId=='common'||!i.categoryId);
    },
    allGroups(){
      return this.myChannelGroups.concat(this.myPrichatChannelGroups)
    }
  },
  beforeCreate() { 

  },
  created() { 
     this.initImClient()
  },
  mounted() {
      console.log(this.$route);
      var that=this;
     
      this.loadImDataFromLocal('listMyChannelGroups'); 
      this.loadImDataFromLocal('listMyPrichatChannelGroups');  
      

    this.channelListHeight = (document.body.clientHeight - 130) + 'px'
    window.onresize = () => {
      return (() => {
        this.channelListHeight = (document.body.clientHeight - 130) + 'px'
      })()
    }
  },
  components: { GroupIcon, StatusOnlineIcon, StatusOfflineIcon, StatusAwayIcon, 
    StatusDndIcon, StatusOnlineAvatar, StatusOfflineAvatar, StatusAwayAvatar, StatusDndAvatar,
    EditPersonalInfo,
    CreatePrichatChannelGroup,
    CreateChannelGroup,
    ChangePassword,
    MessageDialog
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::-webkit-scrollbar {
  width: 5px;
  height: 5px;
  background-color: #F0F0F0;
}
::-webkit-scrollbar-thumb {
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  -ms-border-radius: 2px;
  -o-border-radius: 2px;
  border-radius: 2px;
  background: rgba(0,0,0,.2);
}
::-webkit-scrollbar-track {
  background: rgba(0,0,0,.1);
}
.body-container {
    height: 100%;
    background-color: #fff;
    overflow: hidden;
}
.sidebar {
  width: 220px;
  float: left;
  background-color: #1C5CB9;
  .header {
    background-color: #0A53A4;
    height: 85px;
    width: 100%;
    position: relative;
    .avatar {
    width: 55px;
    height: 55px;
    margin: 19px 0px auto 5px;
    background-color: #DF016E;
    border-radius: 36px;
    text-align: center;
    line-height: 23px;
    color: #fff;
    font-weight: bold;
    float: left;
    overflow: hidden;
    padding: 7px 7px 7px 7px;
      img {
        width: 36px;
        height: 36px;
        display: block;
        border-radius: 36px;
      }
    }
    #status-dropdown {
      cursor: pointer;
    }
    .status {
      border-radius: 15px;
      bottom: -4px;
      height: 15px;
      line-height: 0;
      margin: 0;
      position: absolute;
      left: 47px;
      top: 58px;
      width: 15px;
      svg {
        max-height: 11px;
        position: relative;
        top: 2px;
      }
      .icon-container {
        :after {
          border-radius: 20px;
          height: 10px;
          left: 4px;
          position: absolute;
          top: 4px;
          width: 10px;
        }
      }             
    }
    .status-edit {
      border-radius: 15px;
      background-color: #fff;
      width: 13px;
      height: 13px;
      left: 50px;
      top: 58px;
      position: absolute;
      text-align: center;    
      svg {
        position: relative;
        top: -2px;
        padding: 0;
        margin: 0;
      } 
    }      
    .status-selector:hover > .status {
      display: none;
    }
    .status-selector > .status {
      display: inherit;
    }
    .status-selector > .status-edit {
      display: none;
    }
    .status-selector:hover > .status-edit {
      display: inherit;
    }
    .nickname {
      color: #fff;
      padding-top: 4px;
      margin-left: 6px;
      float: left;
    }
    .dropdown-icon {
      border-radius: 36px;
      fill: #D0DDEC;
      float: right;
      height: 36px;
      line-height: 36px;
      position: relative;
      text-align: center;
      width: 36px;
      margin-top: 18px;
      cursor: pointer;
      &:hover {
        fill: #fff;
      }
    }
  }

  .channel-search-container {
    height: 38px;
    padding: 3px 5px 0 5px; 
  }
  
  .channel-container {
    width: 219px;
    overflow: auto;
  }

  .nav-channel {
    margin: 0;
    padding: 0;
    color: #97B8DD;
    list-style: none;
    .channel-header {
      padding: 0 2px 0 10px;
      line-height: 36px;
      span {
        font-weight: bold;
      }
      .add-channel-btn {
        float: right;
        font-size: 28px;
        margin-top: -4px;
        color: #D0DDEC;
        cursor: pointer;
        background: transparent;
        border: none;
        font-family: inherit;
        &:hover {
          color: #fff;
        }
      }
    }
    .channel-item {
      padding-left: 3px;
      &:hover {
        background-color: #1F77BA;
      }
      a {
        display: block;
        -webkit-transition: none 1s;
        transition-delay: 0s;
        -moz-transition: none 1s;
        -o-transition: none 1s;
        transition: none false false 1s;
        text-align: left;
        width: 100%;
        border-radius: 0;
        line-height: 30px;
        height: 30px;
        outline: none;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 14px;
        color: #fff;
        white-space: nowrap;
        svg {
          height: 14px;
          width: 14px;
          left: 10px;
          top: 0px;
          max-height: initial;
          position: relative;
          z-index: 1;
        } 
      }
      .status {
        display: inline-block;
        position: relative;
        padding: 0 0 0 10px;
        margin-top: 1px;
      }     
      .channel-item-name {
        display: inline-block;
        width: 131px;
        max-width: 131px;
        overflow: hidden;
        text-overflow: ellipsis;
        vertical-align: top;
      }
      .channel-item-name-selected {
        font-weight: bold;
        color: #F6F7C0;
      }
      .unread-message-count {
        display: inline-block;
        width: 20px; 
        height: 20px;
        margin-top: -7px;
        background-color: red;
        border-radius: 20px;
        text-align: center;
        line-height: 20px;
        color: #fff;
        vertical-align: middle;
        font-size: 12px;
      }
      .unread-message-count-hide {
        display: inline-block;
        width: 20px;
      }      
      .has-close {
        &:hover{
          .btn-close {
            opacity: 0.8;
            display: inline-block;
            text-decoration: none;
          }
          .channel-item-name {
            max-width: 131px;
            min-width: 131px;
          }
        }
      }
      .btn-close {
        opacity: 0;
        display: none;
        font-size: 20px;
        font-weight: 600;
        right: 29px;
        height: 16px;
        line-height: 16px;
        margin: -7px 0 0 0;
        padding-bottom: 2px;
        vertical-align: middle;
        &:hover {
          opacity: 1;
          background-color: #F23724;
        }
      }
    }
    .channel-item-active {
      padding-left: 0px;
      background-color: #186CC1;
      border-left: solid 3px #279EFF;
    }
  }
  .first-nav-channel {
    padding-top: 2px;
  }
}
.content {
  flex: 1;
}
.status-tooltip {
  font-size: 8px;
  color: #7C7A74;
  margin-top: -15px;
}
</style>